package net.thxjj.adminServer.controller;

import cmcciot.onenet.nbapi.sdk.api.online.GetDevicesOpe;
import cmcciot.onenet.nbapi.sdk.entity.GetDevice;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ctg.ag.sdk.biz.AepDeviceEventClient;
import com.ctg.ag.sdk.biz.AepDeviceManagementClient;
import com.ctg.ag.sdk.biz.AepDeviceStatusClient;
import com.ctg.ag.sdk.biz.aep_device_event.QueryDeviceEventListRequest;
import com.ctg.ag.sdk.biz.aep_device_event.QueryDeviceEventListResponse;
import com.ctg.ag.sdk.biz.aep_device_management.QueryDeviceListRequest;
import com.ctg.ag.sdk.biz.aep_device_management.QueryDeviceListResponse;
import com.ctg.ag.sdk.biz.aep_device_status.GetDeviceStatusHisInPageRequest;
import com.ctg.ag.sdk.biz.aep_device_status.GetDeviceStatusHisInPageResponse;
import net.thxjj.adminServer.controller.base.BaseController;
import net.thxjj.adminServer.entity.*;
import net.thxjj.adminServer.entity.aep.DevLog;
import net.thxjj.adminServer.entity.aep.HeartData;
import net.thxjj.adminServer.entity.aep.LoginData;
import net.thxjj.adminServer.entity.aep.SmokeData;
import net.thxjj.adminServer.service.*;
import net.thxjj.adminServer.util.ParameterMap;
import net.thxjj.adminServer.util.Tools;
import net.thxjj.adminServer.websocket.mq.JSONOneNet2DeviceUtil;
import net.thxjj.sitermodel.Device;
import net.thxjj.sitermodel.Product;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.*;

@RestController
@RequestMapping("/api/update")
public class UpdateApiController extends BaseController {
    @Autowired
    private IDeviceService iDeviceService;
    @Autowired
    private IDevLogService iDevLogService;
    @Autowired
    private IProductService iProductService;
    @Autowired
    private IProfileLogService iProfileLogService;
    @Autowired
    private IProfileGCService iProfileGCService;

    /**
     * 同步设备列表（NBIOT电信平台）
     * @return
     */
    @RequestMapping(value="/devices",method= RequestMethod.GET)
    @ResponseBody
    public Object getDevicesFromAEP(){

        String prod_key = this.getParameterMap().getString("prod_key");
        if(Tools.isEmpty(prod_key)){
            return ResponseModel.getModel(ResultEnum.PARAMETER_EMPTY_ERROR,null);
        }

        Product product = iProductService.getProduct(prod_key);
        if(product==null || Tools.isEmpty(product.getApiKey())){
            return ResponseModel.getModel("查询数据为空",400,null);
        }

        if(!product.getPlatform().equals("aep")&&!product.getPlatform().equals("onenet")){
            return ResponseModel.getModel("不支持查询",400,null);
        }

        List<Device> devicelist = new ArrayList<>();
        int page = 1;
        boolean flag_end = false;
        //aep平台查询数据
        if(product.getPlatform().equals("aep")){
            AepDeviceManagementClient client = AepDeviceManagementClient.newClient()
                    .appKey(Const.APPKEY).appSecret(Const.APPSECRET)
                    .build();
            while (!flag_end){
                try {
                    QueryDeviceListRequest request = new QueryDeviceListRequest();
                    request.setParamMasterKey(product.getApiKey());	// single value
                    request.setParamProductId(product.getProdKey());	// single value
                    request.setParamPageNow(page);	// single value
                    request.setParamPageSize(100);	// single value
                    // request.addParamPageSize(pageSize);	// or multi values
                    QueryDeviceListResponse response = client.QueryDeviceList(request);
                    String body = new String(response.getBody());
                    JSONObject jsonObject = JSON.parseObject(body);
                    JSONObject result = jsonObject.getJSONObject("result");

                    JSONArray list = result.getJSONArray("list");

                    log.info("设备列表："+list.toJSONString());
                    List<Device>  collection = new ArrayList<>();
                    if(list.size()>0){
                        for(int i=0;i<list.size();i++){
                            JSONObject jsonObjecta = list.getJSONObject(i);
                            Device ad = JSONObject.parseObject(jsonObjecta.toJSONString(),Device.class);
                            ad.setProdKey(jsonObjecta.getString("productId"));
                            collection.add(ad);
                        }
                        devicelist.addAll(collection);
                    }

                    if(collection.size()<100){
                        flag_end = true;
                    }else{
                        page++;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    return ResponseModel.getModel(ResultEnum.AEP_FAIED, null);
                }
            }
            client.shutdown();
        }else{
            //onnet平台查询数据
            while (!flag_end){
                GetDevicesOpe deviceOpe = new GetDevicesOpe(product.getApiKey());
                GetDevice getDevice = new GetDevice(page);
                JSONObject data = deviceOpe.operation(getDevice, null).getJSONObject("data");
                JSONArray devices = data.getJSONArray("devices");
                List<Device> list = new ArrayList<Device>();
                for (int i=0;i<devices.size();i++){
                    JSONObject jsonObject = devices.getJSONObject(i);
                    Device device =  JSONOneNet2DeviceUtil.getDeviceFrom(jsonObject);
                    list.add(device);
                }

                if(list.size()>0){
                    devicelist.addAll(list);
                    long total_count = data.getLongValue("total_count");
                    long pagenow = data.getLongValue("page");

                    if(pagenow>=total_count){
                        flag_end = true;
                    }else{
                        page++;
                    }
                }else{
                    flag_end = true;
                }


            }
        }



       List<Device>  list = iDeviceService.getDeviceListByProductId(prod_key);
        List<Device> aja = new ArrayList<>();
        for (int i=0;i<list.size();i++){
           Device da = list.get(i);
           boolean flag_has = false;
           for(Device device:devicelist){
               if(da.getDeviceId().equals(device.getDeviceId())){
                   flag_has = true;
                   break;
               }
           }
           if(!flag_has){
               aja.add(da);
           }
       }



        List<Device> aja2 = new ArrayList<>();
        for (int i=0;i<devicelist.size();i++){
            Device da = devicelist.get(i);
            boolean flag_has = false;
            for(Device device:list){
                if(da.getDeviceId().equals(device.getDeviceId())){
                    flag_has = true;
                    break;
                }
            }
            if(!flag_has){
                aja2.add(da);
            }
        }

        iDeviceService.setDevicesUpdate(aja,devicelist);

        ParameterMap data = new ParameterMap();
        data.put("deviceAdd",aja2);
        data.put("deviceOut",aja);


        return ResponseModel.getModel(ResultEnum.SUCCESS, data);
    }

    /**
     * 同步设备历史数据(事件)（NBIOT电信平台）
     * @return
     */
    @RequestMapping(value="/deviceEvents",method= RequestMethod.GET)
    @ResponseBody
    public Object getDeviceEvents(){

        String deviceId = this.getParameterMap().getString("deviceId");

        if(StringUtils.isEmpty(deviceId)){
            return ResponseModel.getModel(ResultEnum.PARAMETER_EMPTY_ERROR,null);
        }



        boolean flag = true;
        String page_timestamp = "";
        int n = 0;
        AepDeviceEventClient client = null;
        do {
            try {
                client = AepDeviceEventClient.newClient()
                        .appKey(Const.APPKEY).appSecret(Const.APPSECRET)
                        .build();
                Calendar now = Calendar.getInstance();
                now.add(Calendar.DAY_OF_MONTH, -30*n);
                long end_time_long = now.getTime().getTime();
                now.add(Calendar.DAY_OF_MONTH, -30);
                long start_time_long = now.getTime().getTime();
                JSONObject param = new JSONObject();
                param.put("productId",Const.PRODUCT_ID);
                param.put("deviceId",deviceId);
                param.put("startTime",start_time_long);
                param.put("endTime",end_time_long);
                param.put("pageSize",100);
                param.put("pageTimestamp",page_timestamp);

                QueryDeviceEventListRequest request = new QueryDeviceEventListRequest();
                request.setParamMasterKey(Const.MASTER_APIKEY);
                request.setBody(param.toJSONString().getBytes());	//具体格式见前面请求body说明
                QueryDeviceEventListResponse queryDeviceEventListResponse = client.QueryDeviceEventList(request);
                System.out.println(queryDeviceEventListResponse);
                String body = new String(queryDeviceEventListResponse.getBody());
                JSONObject jsonObject = JSON.parseObject(body);
                int code = jsonObject.getIntValue("code");
                String desc = jsonObject.getString("msg");
                page_timestamp = jsonObject.getString("page_timestamp");

                if(code==0){
                    JSONArray array = jsonObject.getJSONObject("result").getJSONArray("list");
                    if(StringUtils.isEmpty(page_timestamp)){
                        n++;
                        page_timestamp = "";
                        if(array.size()==0){
                            flag = false;
                        }
                    }
                    List<DevLog>  list = JSONObject.parseArray(array.toJSONString(), DevLog.class);
                    if(list.size()>0)
                    iDevLogService.addEvent(list);
                }else{
                    return ResponseModel.getModel(desc,code,null);
                }


            } catch (Exception e) {
                e.printStackTrace();
                return ResponseModel.getModel(ResultEnum.AEP_FAIED,null);
            }
        }
        while (flag);
        client.shutdown();
        return ResponseModel.getModel(ResultEnum.SUCCESS,null);
    }


    /**
     * 同步设备历史数据(状态数据)（NBIOT电信平台）
     * @return
     */
    @RequestMapping(value="/deviceStates",method= RequestMethod.GET)
    @ResponseBody
    public Object getDeviceStates() {
        String deviceId = this.getParameterMap().getString("deviceId");
        Calendar now = Calendar.getInstance();
        long curtime = now.getTime().getTime();
        now.add(Calendar.DAY_OF_MONTH, -30);
        long histime = now.getTime().getTime()+10000;
        AepDeviceStatusClient client = AepDeviceStatusClient.newClient()
                .appKey(Const.APPKEY).appSecret(Const.APPSECRET)
                .build();
        JSONObject param = new JSONObject();
        param.put("productId",Const.PRODUCT_ID);
        param.put("deviceId",deviceId);
        param.put("begin_timestamp",histime);
        param.put("end_timestamp",curtime);
        param.put("page_size",100);
        boolean flag = true;
        String page_timestamp = "";

        do {
            List<HeartData> heartDataList = new ArrayList<>();
            List<SmokeData> smokeDataList = new ArrayList<>();
            List<LoginData> loginDataList = new ArrayList<>();
            try {
                GetDeviceStatusHisInPageRequest request = new GetDeviceStatusHisInPageRequest();
                param.put("page_timestamp",page_timestamp);
                request.setBody(param.toJSONString().getBytes());	//具体格式见前面请求body说明
                GetDeviceStatusHisInPageResponse statusHisInPageResponse = client.getDeviceStatusHisInPage(request);
                String body = new String(statusHisInPageResponse.getBody());
                JSONObject jsonObject = JSON.parseObject(body);
                int code = jsonObject.getIntValue("code");
                String desc = jsonObject.getString("desc");
                page_timestamp = jsonObject.getString("page_timestamp");
                JSONArray array = jsonObject.getJSONArray("deviceStatusList");
                if(code==0){
                    if(StringUtils.isEmpty(page_timestamp)){
                        flag = false;
                    }
                    for(int i=0;i<array.size();i++){
                        JSONObject obj = array.getJSONObject(i);
                        if(obj.containsKey("heartbeat_time")){
                            HeartData heartData = JSONObject.parseObject(obj.toJSONString(), HeartData.class);
                            heartData.setDeviceId(deviceId);
                            heartDataList.add(heartData);
                        }
                        else if(obj.containsKey("smoke_state")){
                            SmokeData smokeData = JSONObject.parseObject(obj.toJSONString(), SmokeData.class);
                            smokeData.setDeviceId(deviceId);
                            smokeDataList.add(smokeData);
                        }else if(obj.containsKey("tau_flag")){
                            LoginData loginData = JSONObject.parseObject(obj.toJSONString(), LoginData.class);
                            loginData.setDeviceId(deviceId);
                            loginDataList.add(loginData);
                        }


                    }
                    iDevLogService.addData(heartDataList,smokeDataList,loginDataList);
                }else{
                    return ResponseModel.getModel(desc,code,null);
                }


            } catch (Exception e) {
                e.printStackTrace();
                return ResponseModel.getModel(ResultEnum.AEP_FAIED,null);
            }
        }
        while (flag);
        client.shutdown();
        return ResponseModel.getModel(ResultEnum.SUCCESS,null);
    }

    /**
     * http同步所有设备历史数据(状态数据)（NBIOT电信平台）
     * @return
     */
    @RequestMapping(value="/allDataUpdate",method= RequestMethod.GET)
    @ResponseBody
    public Object allDataUpdate() {

        List<Device>  list = iDeviceService.getDeviceListByProductId(Const.PRODUCT_ID);
        for (int i=0;i<list.size();i++){
            Device device = list.get(i);
            iDevLogService.updateDeviceData(device);
        }

        return ResponseModel.getModel(ResultEnum.SUCCESS,null);
    }


    /**
     * http同步所有设备历史数据(事件数据)（NBIOT电信平台）
     * @return
     */
    @RequestMapping(value="/allEventUpdate",method= RequestMethod.GET)
    @ResponseBody
    public Object allEventUpdate() {

        List<Device>  list = iDeviceService.getDeviceListByProductId(Const.PRODUCT_ID);
        for (int i=0;i<list.size();i++){
            Device device = list.get(i);
            iDevLogService.updateDeviceEvent(device);
        }

        return ResponseModel.getModel(ResultEnum.SUCCESS,null);
    }

    /**
     * http同步所有PROFILE设备历史数据（NBIOT电信平台）
     * @return
     */
    @RequestMapping(value="/allProfileUpdate",method= RequestMethod.GET)
    @ResponseBody
    public Object allProfileUpdate() {

        List<Device>  list = iDeviceService.getDeviceListByProductId(Const.PROFILE_PRODUCT_ID);
        for (int i=0;i<list.size();i++){
            Device device = list.get(i);
            iProfileLogService.updateDeviceData(device);
        }

        return ResponseModel.getModel(ResultEnum.SUCCESS,null);
    }


    /**
     * http同步所有PROFILE GAS-CO设备历史数据（NBIOT电信平台）
     * @return
     */
    @RequestMapping(value="/allProfileUpdateGAS",method= RequestMethod.GET)
    @ResponseBody
    public Object allProfileUpdateGAS() {

        List<Device>  list = iDeviceService.getDeviceListByProductId(Const.PROFILE_PRODUCT_ID_GC);
        for (int i=0;i<list.size();i++){
            Device device = list.get(i);
            iProfileGCService.updateDeviceData(device);
        }


        return ResponseModel.getModel(ResultEnum.SUCCESS,null);
    }

    /**
     * http同步所有PROFILE GAS-CO设备历史数据（NBIOT电信平台）
     * @return
     */
    @RequestMapping(value="/allProfileUpdateGAS_2",method= RequestMethod.GET)
    @ResponseBody
    public Object allProfileUpdateGAS_2() {

        List<Device>  list = iDeviceService.getDeviceListByProductId(Const.PROFILE_PRODUCT_ID_GC_2);
        for (int i=0;i<list.size();i++){
            Device device = list.get(i);
            iProfileGCService.updateDeviceData(device);
        }


        return ResponseModel.getModel(ResultEnum.SUCCESS,null);
    }

}
